package com.cskaoyan.gateway.controller.user;

import com.cskaoyan.gateway.form.user.LoginForm;
import com.cskaoyan.gateway.form.user.RegisterForm;
import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.commons.tool.utils.CookieUtil;
import com.mall.user.IKaptchaService;
import com.mall.user.IUserVerifyService;
import com.mall.user.annotation.Anoymous;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dto.*;
import com.mall.user.intercepter.TokenIntercepter;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.shaded.com.google.common.base.Verify;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @program: dragon-mall
 * @description: 用户注册、登录、验证 等无需登录验证的接口
 * @author: Keyu Li
 * @create: 2021-12-11 21:32
 **/

@Anoymous
@Slf4j
@RestController
@RequestMapping("/user")
public class AuthController {

    @Reference(timeout = 30000, retries = 0, check = false)
    IUserVerifyService verifyService;

    @Reference(timeout = 30000, retries = 0, check = false)
    IKaptchaService kapService;

    private final String KAPTCHA_UUID = "kaptcha_uuid";

    @PostMapping("register")
    public ResponseData register(@RequestBody RegisterForm form, HttpServletRequest httpRequest) {
        // 记录日志
        log.info("用户注册 --> 用户名:{} 用户邮箱:{}", form.getUserName(), form.getEmail());
        // 1 验证码：隔壁验证码验证的controller直接抄过来……
        KaptchaCodeRequest kapRequest = new KaptchaCodeRequest();
        String kapUuid = CookieUtil.getCookieValue(httpRequest, KAPTCHA_UUID);
        kapRequest.setUuid(kapUuid);
        kapRequest.setCode(form.getCaptcha());
        KaptchaCodeResponse kapResponse = kapService.validateKaptchaCode(kapRequest);
        if (!kapResponse.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())) {
            // 如果验证码不一致，直接返回
            return new ResponseUtil<>().setErrorMsg(kapResponse.getMsg());
        }

        // 2 registerform 转换为 userRegisterRequest
        UserRegisterRequest request = new UserRegisterRequest();
        request.setUserName(form.getUserName());
        request.setEmail(form.getEmail());
        request.setUserPwd(form.getUserPwd());

        // 3 service层操作：插入当前用户到 用户表 和 用户验证表
        UserRegisterResponse response = verifyService.registerUser(request);
        // 4 根据 userRegisterResponse 信息返回
        if (SysRetCodeConstants.SUCCESS.getCode().equals(response.getCode())) {
            return new ResponseUtil<>().setData(null);
        }
        return new ResponseUtil<>().setErrorMsg(response.getMsg());
    }

    @PostMapping("login")
    public ResponseData login(@RequestBody LoginForm form, HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
        // 记录日志
        log.info("用户登录 --> 用户名:{}, 时间:{}", form.getUserName(),new Date());
        // 1 验证验证码
        KaptchaCodeRequest kapRequest = new KaptchaCodeRequest();
        String kapUuid = CookieUtil.getCookieValue(httpRequest, KAPTCHA_UUID);
        kapRequest.setUuid(kapUuid);
        kapRequest.setCode(form.getCaptcha());
        KaptchaCodeResponse kapResponse = kapService.validateKaptchaCode(kapRequest);
        if (!kapResponse.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())) {
            // 如果验证码不一致，直接返回
            return new ResponseUtil<>().setErrorMsg(kapResponse.getMsg());
        }

        // 2 loginForm 转换为 userLoginRequest
        UserLoginRequest request = new UserLoginRequest();
        request.setUserName(form.getUserName());
        request.setPassword(form.getUserPwd());

        // 3 service 操作，验证用户名和密码
        UserLoginResponse response = verifyService.login(request);

        // 4 根据 response 返回
        if (SysRetCodeConstants.SUCCESS.getCode().equals(response.getCode())) {
            // 4.1 在HttpServletResponse设置cookie：key为access_token，value为token
            // maxAge 单位是 秒
            Cookie cookie = CookieUtil.genCookie(TokenIntercepter.ACCESS_TOKEN, response.getToken(), "/", 30*60);
            cookie.setHttpOnly(true);
            httpResponse.addCookie(cookie);
            return new ResponseUtil<>().setData(response);
        }
        return new ResponseUtil<>().setErrorMsg(response.getMsg());
    }



    /*
    * 用户验证邮箱
    * http://localhost:8080?uuid=xxxx&userName=xxxx
    * */
    @GetMapping("verify")
    public ResponseData verify( UserVerifyRequest request){
        // service 操作
        UserVerifyResponse response = verifyService.verify(request);

        // 根据 response返回
        if (SysRetCodeConstants.SUCCESS.getCode().equals(response.getCode())) {
            return new ResponseUtil<>().setData(null);
        }
        return new ResponseUtil<>().setErrorMsg(response.getMsg());
    }

}
